using System.Threading.Tasks;

namespace Sidvall.Business
{
    public sealed class TaskContext
    {
        #region Public Members

        public Sidvall.Business.DataPortalResult Result { get; set; }

        #region Exception

        private System.Exception _Exception;
        public System.Exception Exception
        {
            get
            {
                return _Exception;
            }
            set
            {
                _Exception = value;
                if (_Exception != null)
                    this.Result = DataPortalResult.Failed;
            }
        }

        #endregion
        #region Tasks

        private System.Collections.ObjectModel.Collection<Task> _Tasks;
        public System.Collections.ObjectModel.Collection<Task> Tasks
        {
            get
            {
                if (_Tasks == null)
                    _Tasks = new System.Collections.ObjectModel.Collection<Task>();
                return _Tasks;
            }
        }

        #endregion

        #region Copy

        public TaskContext Copy()
        {
            var item = new TaskContext()
            {
                Exception = this.Exception,
                Result = this.Result,
            };
            return item;
        }

        #endregion
        #region DoTaskAsync

        public async Task DoTaskAsync()
        {
            await DoTaskAsync(true).ConfigureAwait(false);
        }
        public async Task DoTaskAsync(bool throwException)
        {
            try
            {
                foreach (var task in this.Tasks)
                {
                    if (task != null)
                        await task.ConfigureAwait(false);
                }
            }
            finally
            {
                this.Tasks.Clear();
            }
            if (throwException)
            {
                if (this.Exception != null)
                    throw this.Exception;
            }
        }

        #endregion

        #endregion
        #region Constructors

        public TaskContext()
        {
        }

        #endregion
    }
}
